//
//  ArchViewController.m
//  数据的增删改查
//
//  Created by Clement_Gu on 16/3/15.
//  Copyright © 2016年 小白. All rights reserved.
//

#import "ArchViewController.h"
#import "StudentModel.h"
@interface ArchViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic,strong)UITextField *txtID;
@property (nonatomic,strong)UITextField *txtName;
@property (nonatomic,strong)UITextField *txtAge;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *mArrList;
@property (nonatomic,strong)NSMutableArray *mArrGetList;
@end

@implementation ArchViewController
//懒加载 重写getter
-(NSMutableArray *)mArrList
{
    if (_mArrList == nil) {
        //判断文档是否存在 如果存在则在原文件中读取
        NSFileManager *fmManager = [NSFileManager defaultManager];
        if ([fmManager fileExistsAtPath:[self plistPath]]) {
            //解档
            //1.读出数据
            NSData *data = [NSData dataWithContentsOfFile:[self plistPath]];
            //2.创建解档对象
            NSKeyedUnarchiver *unArch = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
            //3.读取
            _mArrList = [unArch decodeObjectForKey:@"Student"];
            //4完成
            [unArch finishDecoding];
        }
        else
        {
            //否则新建数据
            _mArrList  = [NSMutableArray array];
        }
    }
    
    return _mArrList;
}


//在页面加载前
-(void)loadView
{
    //将ViewContrller中的View变为UIContrl的对象
    UIControl *control = [[UIControl alloc]initWithFrame:[UIScreen mainScreen].bounds];
    [self setView:control];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.txtID = [self buidTxt:CGRectMake(120, 50, 150, 35) AndKeboardType:UIKeyboardTypeNumberPad];
    self.txtName = [self buidTxt:CGRectMake(120, 120, 150, 35) AndKeboardType:UIKeyboardTypeNumbersAndPunctuation];
    self.txtAge = [self buidTxt:CGRectMake(120, 190, 150, 35) AndKeboardType:UIKeyboardTypeNumberPad];
    [self buidLabel:CGRectMake(70, 50, 50, 40) andText:@"学号"];
    [self buidLabel:CGRectMake(70, 120, 50, 40) andText:@"名字"];
    [self buidLabel:CGRectMake(70, 190, 50, 40) andText:@"年龄"];
    [self buidBtn:CGRectMake(15, 250, 50, 40) AndName:@"添加" AndEvent:@selector(add)];
    [self buidBtn:CGRectMake(65, 250, 50, 40) AndName:@"删除" AndEvent:@selector(remove)];
    [self buidBtn:CGRectMake(115, 250, 50, 40) AndName:@"修改" AndEvent:@selector(motify)];
    [self buidBtn:CGRectMake(165, 250, 50, 40) AndName:@"查找" AndEvent:@selector(resarch)];
    [self buidBtn:CGRectMake(215, 250, 80, 40) AndName:@"查找全部" AndEvent:@selector(findAll)];
    //添加表格
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(5, 300, 310, 250)];
    self.tableView = tableView;
    [self.view addSubview:tableView];
    //注册单元格模板
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    //声明代理
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //添加点击View页面的事件
    UIControl *control = self.view;
    //设置背景色
    self.view.backgroundColor = [UIColor whiteColor];
    [control addTarget:self action:@selector(resignView) forControlEvents:UIControlEventTouchUpInside];
    
    //    UIControl *vc = [[UIControl alloc]init];
    //
    //    [vc addTarget:self action:@selector(resignView) forControlEvents:UIControlEventTouchUpInside];
}
//创建textFile
-(UITextField *)buidTxt:(CGRect)frame AndKeboardType:(UIKeyboardType)keyboard
{
    UITextField *txtFileID = [[UITextField alloc]initWithFrame:frame];
    [txtFileID setBorderStyle:UITextBorderStyleRoundedRect];
    [txtFileID setKeyboardType:keyboard];
    [self.view addSubview:txtFileID];
    return txtFileID;
}
//创建label
-(void)buidLabel:(CGRect)frame andText:(NSString *)text
{
    UILabel *label = [[UILabel alloc]initWithFrame:frame];
    label.text = text;
    [self.view addSubview:label];
}
//创建button
-(void)buidBtn:(CGRect)frame AndName:(NSString *)name AndEvent:(SEL)sel
{
    UIButton *btn = [[UIButton alloc]initWithFrame:frame];
    [btn setTitle:name forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [btn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
    
}
//点击空白取消编辑状态
-(void)resignView
{
    [self.view endEditing:YES];
}
//plist文件在沙盒的地址
-(NSString *)plistPath
{
    //沙盒路径 然后进入Documents
    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //再从Documents里面添加plist
    NSString *filePath = [path stringByAppendingPathComponent:@"students.arch"];
    NSLog(@"%@",filePath);
    //返回plist路径
    return filePath;
}
//保存数据到plist文件（覆盖以前的数据）
-(void)saveData
{
    //写到文件归档
    //创建可变数据存放data
    NSMutableData *mData = [NSMutableData data];
    //创建归档对象
    NSKeyedArchiver *arch = [[NSKeyedArchiver alloc]initForWritingWithMutableData:mData];
    //归档数组对象（数组本身支持归档 数组的元素也要支持归档）
    [arch encodeObject:self.mArrList forKey:@"Students"];
    //完成归档
    [arch finishEncoding];
    //数据存入文件
    [mData writeToFile:[self plistPath] atomically:YES];
    
}

//弹出框方法
-(void)showAlert:(NSString *)title AndMessage:(NSString *)message
{
    //弹出错误信息
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    //添加取消键
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
    //弹到页面
    [self presentViewController:alert animated:YES completion:nil];
    //执行action
    [alert addAction:action];
}
//取数据
-(void)getData
{
    //取得students.arch文件的数据作为tableview显示的数据
    //读出数据
    NSData *data = [NSData dataWithContentsOfFile:[self plistPath]];
    //创建解档对象
    NSKeyedUnarchiver *unArch = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    //从解档对象中解档student 和归档使用相同的key
    self.mArrGetList = [unArch decodeObjectForKey:@"Students"];
    //完成解档
    [unArch finishDecoding];
  
    
}

-(void)add
{
    if (self.mArrList == nil) {
        //创建存储字典
        StudentModel  *stuM = [[StudentModel alloc]initWithId:self.txtID.text andName:self.txtName.text andAge:self.txtAge.text];
  
        //添加进数组
        [self.mArrList addObject:stuM];
        //保存数据
        [self saveData];
    }
    else
    {
        //创建监控数据
        int count = 0;
        //遍历数组
        for (StudentModel *element in self.mArrList){
            //判断数组里为MutableDictionary
//            if ([element isKindOfClass:[StudentModel class]]) {
                //判断有没有重复的id
                if ([element.stuID isEqualToString:self.txtID.text]) {
                    [self showAlert:@"警告" AndMessage:@"此学生信息已经存在！"];
                    count++;
                }
//            }
        }
        if (count == 0) {
            //创建存储字典
            StudentModel *stuM = [[StudentModel alloc]initWithId:self.txtID.text andName:self.txtName.text andAge:self.txtAge.text];
            //添加进数组
            [self.mArrList addObject:stuM];
            //保存数据
            [self saveData];
            
        }
    }
}
-(void)remove
{
    //1.遍历数组
    for (StudentModel *element in self.mArrList) {
        //2.以学生学号为判断条件
        if ([element.stuID isEqualToString:self
             .txtID.text]) {
            //执行删除操作
            [self.mArrList removeObject:element];
            //跳出
            break;
        }
    }
    //保存数据
    [self saveData];
}
-(void)motify
{
    //设定监测数据
    int count = 0;
    //1.遍历寻找
    for (StudentModel *element in self.mArrList) {
        //2.以学号为基准进行判断
        if ([element.stuID isEqualToString:self.txtID.text]) {
            //修改信息
            element.stuName = self.txtName.text;
            element.stuAge = self.txtAge.text;
            count++;
            break;
        }
        
        
    }
    //声明
    if (!count) {
        [self showAlert:@"信息错误" AndMessage:@"请输入正确的学号！"];
        
    }
    //保存数据
    [self saveData];
}
-(void)resarch
{
    //1.遍历
    for (StudentModel *element in self.mArrList) {
        //2.以学生ID进行搜索
        if ([element.stuID isEqualToString:self.txtID.text]) {
            //3.显示
            self.txtName.text = element.stuName;
            self.txtAge.text = element.stuAge;
            break;
        }
    }
}
-(void)findAll
{
    //取arch文件里面的数据
    //解档然后取数据
    [self getData];
    //刷新数据
    [self.tableView reloadData];
    
}
//设置section的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.mArrGetList.count;
}

//表格数据源@requied
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return  3;
}


//单元格的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //复用单元格
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    //第一层数组的元素为dictionary
    StudentModel *stuM = self.mArrGetList[indexPath.section];
    //row的行数为dictionary的key的个数
    //并且排序
//    NSArray *arr = [[dic allKeys] sortedArrayUsingSelector:@selector(compare:)];
        NSMutableArray *mArr = [NSMutableArray array];
            [mArr addObject:stuM.stuID];
            [mArr addObject:stuM.stuName];
            [mArr addObject:stuM.stuAge];
    
    //单元格内容
    //    cell.textLabel.text = mArr[indexPath.row];
    cell.textLabel.text = mArr[indexPath.row];
    return cell;
}

//sectionhead 内容
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    //第一层数组的元素为dictionary
   StudentModel *stuM = self.mArrGetList[section];
    //显示ID作为段头
    return stuM.stuID;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
